import React from 'react';
import { inject, observer } from 'mobx-react';
import {Icon,message,Tooltip} from 'antd'
import {WeaBrowser,WeaLocaleProvider,WeaTools, WeaUpload } from 'ecCom';
import NewLinkeb from '../../../public/newlinked/NewLinkeb';
import PlanDetail from '../../plan/planReportView/PlanDetail';
import * as Util from '../../../util/Util';
//import ReactDOM from 'react-dom';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
@inject('taskDetailStore')
@observer
export default class RelateInfo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            planvisible:false,//报告详情显隐
            plandetailid:'',//报告详情id
        }
        this.mirror = {
            37: "/spa/document/index.jsp?id=",
            7: "/spa/crm/static/index.html#/main/crm/customerView?customerId=",
            152: "/workflow/request/ViewRequestForwardSPA.jsp?requestid=",
            8: "/spa/prj/index.html#/main/prj/projectCard?prjid=",
            1:'/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/',
            "wrlgoal":'/spa/workrelate/static/index.html?#/main/workrelate/goal/goalDetail?id=',
            //"wrlplan":'/spa/workrelate/static/index.html#/main/workrelate/plan/planView?planid='
        }
    }
    componentWillMount() {//一些初始化请求
        WeaTools.callApi('/api/workrelate/common/getRelateURL', 'GET').then((data) => {
            if(data.status){
                this.mirror[7] = data.result[7];
            }
        })
    }
    componentDidMount(){
        const{taskDetailStore} = this.props;
        if(taskDetailStore.spinning){
            taskDetailStore.spinning = false;
        }
    }
    getRelateTopInfo(datas){//相关信息顶部
        let {canEdit,canShow,editParams,iconArray,category,maxUploadSize} = this.props.taskDetailStore;
        return datas && datas.length>0 && datas.map((element,idx)=>{
            return <div className="relate-info-link"><i className={iconArray[element.columninfo]}/>
            {canEdit && element.type==6 && <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@squiux@${element.columninfo}`} uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
                                            category={category} maxUploadSize={maxUploadSize} viewAttr={canShow ? '2' : '1'}
                                            onChange={(ids, datas) =>this.uploadChange(ids,datas)}
                                            onUploading={(status)=>this.onUploading(status)}>
                                            <span className="relate-info-link-span" title={getLabel(element.languageid,element.name)}>{getLabel(element.languageid,element.name)}</span>
                                        </WeaUpload>}
            {canEdit && element.type==2 && <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@9hisgp@${element.columninfo}`} type={element.browstype} replaceDatas={toJS(editParams[element.columnarray])} onChange={(ids, names, datas) => this.onChangeBrowser(ids,names,datas,element.columninfo,element.columnarray)} 
            title={getLabel(element.languageid,element.name)} icon={iconArray[element.columninfo]} isSingle={element.browssingle} viewAttr={canShow ? '2' : '1'} customized memorise={true}>
                                <span className="relate-info-link-span" title={getLabel(element.languageid,element.name)}>{getLabel(element.languageid,element.name)}</span>
                                </WeaBrowser>}
            {!canEdit && <div class="wea-browser customized wea-field-readonly "><div><span class="relate-info-link-span" title={getLabel(element.languageid,element.name)}>{getLabel(element.languageid,element.name)}</span></div></div>}
            </div>;
        });
    }
    getRelateShowInfo(datas,type){//相关信息显示
        const{taskDetailStore} = this.props;
        const {iconArray} = taskDetailStore;
        if(type==1){
            const{editParams,canEdit,canShow} = taskDetailStore;
            return datas && datas.length>0 && datas.map((element,idx)=>{
                return <div className={(editParams[element.columnarray].length==0?"relate-info-type relate-ishidden":"relate-info-type")}>
                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@hwtbxu@${element.columninfo}`} title={getLabel(element.languageid,element.name)}><div className="relate-info-type-div"><i className={iconArray[element.columninfo]}/></div></Tooltip>
                            <NewLinkeb ecId={`${this && this.props && this.props.ecId || ''}_NewLinkeb@5orlq8@${element.columninfo}`} _width='20' linkurl={this.mirror[element.browstype]} onLinkClick={(id, name, type,fileid) => this.onLinkClick(id, name, type,element.columninfo,element.columnarray,fileid)} linkdatas={editParams[element.columnarray]} hasdel={canShow} hasdownload={element.columninfo=="fileids"?true:false}/>
                        </div>;
            });
        }else{
            return datas && datas.length>0 && datas.map((element,idx)=>{
                return <div className="relate-info-type">
                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@e0ijpw@${element.columninfo}`} title={element.title}><div className="relate-info-type-div"><i className={iconArray[element.columninfo]} style={{color:"red"}}/></div></Tooltip>
                            <NewLinkeb ecId={`${this && this.props && this.props.ecId || ''}_NewLinkeb@9316u6@${element.columninfo}`} _width='20' linkurl={this.mirror[element.browstype]} onLinkClick={(id, name, type) => this.onLinkClick(id, name, type,element.columninfo)} linkdatas={element.datas} hasdel={false} />
                        </div>;
            })
        }
    }
    planOnClose(){
        this.setState({planvisible:false,plandetailid:''});
    }
    onUploading(status){
        const { taskDetailStore } = this.props;
        if(status == 'uploading'){
            taskDetailStore.spinning = true;
        }else{
            taskDetailStore.spinning = false;
        }
    }
    //相关信息点击和删除
    onLinkClick(id, name, type,typeIds, typeArray,fileid){
        const { taskDetailStore } = this.props;
        if(type==2){
            taskDetailStore.canEdit = false;
            //对IDS进行处理
            let vals = taskDetailStore.editParams[typeIds];
            if (vals.length > 0 && !Util.startWith(vals, ',')) {
                vals = ',' + vals;
            }
            if (vals.length > 0 && !Util.endWith(vals, ',')) {
                vals = vals + ',';
            }
            let sendValue = '';
            let fieldtype = '';
            let _index = vals.indexOf("," + id + ",");
            if (_index > -1 && id != "") {
                vals = vals.substring(0, _index + 1) + vals.substring(_index + (id + "").length + 2);
                if (vals == ',') {
                    vals = '';
                }
                taskDetailStore.editParams[typeIds] = vals;
                if (typeIds == 'fileids') {//附件
                    sendValue = id;
                    fieldtype = 'del';
                }else { //其他
                    sendValue = vals;
                    fieldtype = 'str';
                }
            }
            //对array进行处理
            let array = taskDetailStore.editParams[typeArray];
            array.map((elemnet, index) => {
                if (elemnet.id == id) {
                    taskDetailStore.editParams[typeArray].remove(elemnet);
                }
            });
            this.editTaskInfo(typeIds, sendValue, fieldtype, '', id);
        }else if(type==1){
            if(typeIds=="taskids"){
                taskDetailStore.onNodeClick({key:id});
            }
            if(typeIds=="goalids"){
                window.open('/spa/workrelate/static/index.html?#/main/workrelate/goal/goalDetail?id='+id);
            }
            if(typeIds=="fileids"){
                taskDetailStore.viewDocFiled({id:id,relateId:taskDetailStore.detailKey,type:2,doback:function(){
                    Util.opendoc(id);
                }});
            }
            if(typeIds=="planids"){
                this.setState({planvisible:true,plandetailid:id});
            }
        }else{
            taskDetailStore.viewDocFiled({id:id,relateId:taskDetailStore.detailKey,type:2,doback:function(){
                Util.downloads(fileid);
            }});
        }
    }
   
     /**
   * 即时保存页面修改的值（浏览）
   */
  onChangeBrowser = (ids, names, datas, typeIds, typeArray) => {
    const { taskDetailStore } = this.props;
    if (ids.length > 0) {
        let sendValue = '';
        let idsArray = ids.split(',');
        let canSave = false;
        taskDetailStore.canEdit = false;
        //替换数组
        let newAddValues = Util.ArrayDiffer(taskDetailStore.editParams[typeIds],idsArray,2);
        if(!Util.startWith(ids, ',')){
            ids = ","+ids;
        }
        if(!Util.endWith(ids, ',')){
            ids = ids+",";
        }
        let delValues =  Util.ArrayDiffer(taskDetailStore.editParams[typeIds],ids,1);
        if(newAddValues!="" || delValues!=""){
            taskDetailStore.editParams[typeIds] = ids;
            taskDetailStore.editParams[typeArray] = datas;
            sendValue = ids;
            canSave = true;
        }
        if (canSave) {
            this.editTaskInfo(typeIds, sendValue, 'str', newAddValues,delValues);
        } else {
            taskDetailStore.canEdit = true;
        }
      }else{
        let delvalue = taskDetailStore.editParams[typeIds];
        taskDetailStore.editParams[typeIds] = "";
        taskDetailStore.editParams[typeArray] = [];
        this.editTaskInfo(typeIds, "", 'str', "",delvalue);
      }
    }
    /**上传附件 */
    uploadChange(ids, list) {
        const { taskDetailStore } = this.props;
        if (ids.length > 0) {
            let newAddFileids = '';
            for (let i = 0; i < list.length; i++) {
                let fileA = {};
                if (taskDetailStore.editParams.fileids.indexOf(',' + ids[i] + ',') == -1) {
                    newAddFileids += ids[i] + ',';
                    taskDetailStore.editParams.fileids += ids[i] + ',';
                    fileA.id = ids[i];
                    fileA.name = list[i].filename;
                    fileA.size = list[i].filesize;
                    fileA.fileid = list[i].imagefileid;
                    taskDetailStore.editParams.fileArray.push(fileA);
                }
            }
            if (newAddFileids.length > 0) {
                this.editTaskInfo("fileids", newAddFileids, '');
            }else{
                taskDetailStore.spinning = false;
            }
        }
    }
    /**参数同步修改数据 type修改字段 values修改的值 newAddValues新增的值 delValues 删除的值*/
    editTaskInfo(type, values, fieldtype, newAddValues, delValues,tablename) {
        const { taskDetailStore } = this.props;
        const{detailKey} = taskDetailStore;
        taskDetailStore.canEdit = false;
        taskDetailStore.editTaskInfo({
            taskId: detailKey, fieldname: type, fieldvalue: values, fieldtype: fieldtype, addvalue: newAddValues, delvalue: delValues,tablename:tablename, doback:function() {
                message.success(getLabel(31439,'更新成功'));
            }
        });
    }
    render() {
        const { taskDetailStore:{hasData,relateInfoDatas,asslist}} = this.props;
        const {planvisible,plandetailid} = this.state;
        return (
            <div>
                {hasData && <div className="wea-workrelate-relate-info">
                                <div className="relate-info-top">
                                    <div className="relate-info-all">
                                    {this.getRelateTopInfo(toJS(relateInfoDatas))}
                                    </div>
                                </div>
                                <div className="relate-info-content">  
                                    {this.getRelateShowInfo(toJS(relateInfoDatas),1)}
                                    {this.getRelateShowInfo(toJS(asslist),2)}
                                </div>
                            </div>
                    }
                    {planvisible && <PlanDetail ecId={`${this && this.props && this.props.ecId || ''}_PlanDetail@9zksez`} visible={planvisible} detailid={plandetailid} onClose={()=>this.planOnClose()}/>}
            </div>
        )
    }
};